<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2018/2/23
 * Time: 下午5:06
 */
class Member extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->library('email');
        $this->load->database();
        $this->load->model('user_model');
        $this->load->library('form_validation'); //加载表单验证类库
        $this->load->helper('json');
        $this->load->library('session');
        $this->load->model('bill_model');
        $this->load->model('customer_model');
        $this->load->model('member_model');
        $this->load->helper('common');
        $this->load->library('message');
        $this->load->model('goods_model');
    }

    // 商城加入商品到购物车
    public function index()
    {
        $this->load->view('member/index');
    }

    //判断身份(1:主账户,2:管理账户,3:用户账户)
    public function personal()
    {
        $customer_id = $this->session->customer_id;
        if ($customer_id) {
            $query          = $this->db->query("SELECT * FROM app_customer WHERE id=" . $customer_id);
            $r_info         = $query->row_array();
            $r_info['data'] = $r_info;
            if ($r_info['identity'] == 1) {
                $this->load->view('member/personal_admin', $r_info);
            } elseif ($r_info['identity'] == 2 || $r_info['identity'] == 3) {
                $cost_center           = $this->db->query("SELECT name FROM app_cost_center WHERE id=" . $r_info['cost_center_id']);
                $cost_center           = $cost_center->row_array();
                $r_info['cost_center'] = $cost_center;
                $this->load->view('member/personal_user', $r_info);
            }
        }

    }

    //个人中心 修改主账户资料
    public function admin_edit()
    {
        $customer_id = $this->session->customer_id;
        //            $query = $this->db->query("SELECT * FROM app_customer WHERE id=".$customer_id);
        $post_arr = $this->input->post();
//        $data['id']=$post_arr['id'];
        if (!empty($post_arr['name'])) {
            $data['name'] = $post_arr['name'];
        }
        if (!empty($post_arr['company'])) {
            $data['company'] = $post_arr['company'];
        }
        if (!empty($post_arr['newtel'])) {
            $data['tel'] = $post_arr['newtel'];
        }
        if (!empty($post_arr['newemail'])) {
            $data['email'] = $post_arr['newemail'];
        }
        $customer = $this->db->where('id', $customer_id)->update('app_customer', $data);
        if ($customer) {
            $shop_user_id         = $this->user_model->customer_id_to_shop_user_id($customer_id);
            $data['shop_user_id'] = $shop_user_id;
            $res                  = $this->customer_model->company_user_edit($data);
            send_json(array('code' => 0, 'data' => "", 'msg' => '修改成功'));
//            if ($res['code'] == 200) {
            //                send_json(array('code' => 0, 'data' => "", 'msg' => '修改成功'));
            //            } else {
            //                send_json(array('code' => -1, 'data' => '', 'msg' => "用户修改同步失败,请重新添加或联系管理员"));
            //            }
        } else {
            send_json(array('code' => -1, 'data' => "", 'msg' => '修改失败'));
        }

    }

    //发邮箱验证码
    public function admin_edit_email()
    {
//        $post = $this->input->post();
        //        $code = generate_code(6);//验证码
        //        $this->message->add_msg_session($post['email'], $code);
        //        //   log_message('error', '发送邮件成功，内容为：' . $content);
        //        send_json(array('code' => 0, 'data' => $code, 'msg' => '发送成功'));
        //        exit;

        $customer_id = $this->session->customer_id;
        $post        = $this->input->post();
        //邮箱验证
        if (!empty($post['email'])) {
            $data['email'] = $post['email'];
            // send_json(array('code' => 0, 'data' => '', 'msg' => '发送失败'));
            $sender_name = 'livecn@163.com'; //发邮件人的地址
            $code        = generate_code(6); //验证码
            $to_email    = $data['email']; //收件人 email 地址
            $title       = '你的验证码'; // email 主题:
            $content     = "【文具1号企业站】您的验证码为" . $code . "，请勿向他人泄露验证码。如非本人操作，请忽略。"; //email内容
            $res         = $this->bill_model->send_email($sender_name, $to_email, $title, $content, $mailtype = 'html'); //发送email
            if ($res == true) {

                $this->message->add_msg_session($data['email'], $code);
                //   log_message('error', '发送邮件成功，内容为：' . $content);
                send_json(array('code' => 0, 'data' => $code, 'msg' => '发送成功'));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => '发送失败'));
            }
        }

    }

    //检查email验证码
    public function check_email_code()
    {
        if (!isset($_GET['code']) || !$_GET['code']) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "先填写验证码"));
        } elseif (!isset($_GET['key']) || !$_GET['key']) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "参数错误"));
        } else {
            $re = $this->message->check_msg_session($_GET['key'], $_GET['code']);
            if ($re['code'] == 0) {
                send_json(array('code' => 0, 'data' => '', 'msg' => "验证成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => $re['msg']));
            }
        }
    }

    //手机验证码
    public function admin_edit_tel()
    {
        $post = $this->input->post();
        if (!empty($post['tel'])) {
            $data['tel'] = $post['tel'];
            $code        = generate_code(6);
            $msg         = "【文具1号企业站】您的验证码为" . $code . "，请勿向他人泄露验证码。如非本人操作，请忽略。";
            $res         = $this->message->send_msg($data['tel'], $msg);
            if ($res['code'] == 0) {
                $this->message->add_msg_session($post['tel'], $code);
                send_json(array('code' => 0, 'data' => $code, 'msg' => "发送成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "发送失败"));
            }
        }
    }

    //修改个人中心管理账户,用户账户资料
    public function personal_user_edit()
    {
        $customer_id      = $this->session->customer_id;
        $post             = $this->input->post();
        $data             = '';
        $data['name']     = isset($post['name']) ? $post['name'] : '';
        $data['tel']      = isset($post['tel']) ? $post['tel'] : '';
        $data['email']    = isset($post['email']) ? $post['email'] : '';
        $data['username'] = isset($post['username']) ? $post['username'] : '';
        $customer         = $this->db->where('id', $customer_id)->update('app_customer', $data);
        if ($customer == true) {
            send_json(array('code' => 1, 'data' => '', 'msg' => "修改成功"));
        }
    }

    //发票抬头，发票列表展示
    public function invoice()
    {
        $customer_id = $this->session->customer_id;
        if ($customer_id) {
            $query          = $this->db->query("SELECT * FROM app_invoice WHERE customer_id=" . $customer_id);
            $r_info         = $query->result_array();
            $r_info['data'] = $r_info;
            $this->load->view('member/invoice', $r_info);
        }

    }

    //添加/修改个人中心抬头票
    public function insert_invoice()
    {
        $customer_id = $this->session->customer_id;
//        $query = $this->db->query("SELECT * FROM app_invoice WHERE customer_id=" . $customer_id);
        //        $r_info = $query->row_array();
        $post                         = $this->input->post();
        $data['is_default']           = $post['is_default'];
        $data['invoice_type']         = isset($post['invoice_type']) ? $post['invoice_type'] : "";
        $data['invoice_company_name'] = $post['invoice_company_name'];
        if (empty($data['invoice_company_name'])) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "单位名称不能为空"));
        }
        $data['invoice_code'] = $post['invoice_code'];
        if (empty($data['invoice_code'])) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "识别码不能为空"));
        }
        if ($post['invoice_type'] == 2) {
            $data['invoice_address'] = $post['invoice_address'];
            if (empty($data['invoice_address'])) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "注册地址不能为空"));
            }
            $data['invoice_tel'] = isset($post['invoice_tel']) ? $post['invoice_tel'] : "";
            if (empty($data['invoice_company_name'])) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "联系电话不能为空"));
            }
            $data['invoice_bank'] = $post['invoice_bank'];
            if (empty($data['invoice_bank'])) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "开户银行不能为空"));
            }
            $data['invoice_account'] = $post['invoice_account'];
            if (empty($data['invoice_account'])) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "银行账户不能为空"));
            }
        }
        $data['customer_id'] = $customer_id;

        if (!empty($post['id'])) {
            $data['id'] = $post['id'];
            if ($post['is_default'] == 1) {
                $bool1 = $this->db->where(array("customer_id" => $customer_id))->update('app_invoice', ['is_default' => 0]);
            }
            //抬头发票修改
            $res = $this->db->where(array('customer_id' => $customer_id, 'id' => $data['id']))->update('app_invoice', $data);
            if ($res) {
                $where                = array('id' => $post['id']);
                $row                  = $this->db->select('shop_id')->where($where)->from('app_invoice')->get()->row_array();
                $data['shop_id']      = $row['shop_id'];
                $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($customer_id);
                $user_invoice         = $this->member_model->company_user_invoice($data); //同步
                if ($user_invoice['data']) {
                    send_json(array('code' => 0, 'data' => '', 'msg' => "修改成功"));
                } else {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "同步失败"));
                }
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "修改失败"));
            }

        } else {
            if ($post['is_default'] == 1) {
                $bool1 = $this->db->where(array("customer_id" => $customer_id))->update('app_invoice', ['is_default' => 0]);
            }
            //抬头发票新增
            $invoice    = $this->db->insert('app_invoice', $data);
            $invoice_id = $this->db->insert_id();
            if ($invoice) {
                $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($customer_id);
                $shop_id              = $this->member_model->company_user_invoice($data); //同步
                $where                = array('id' => $invoice_id);
                $user_invoice         = $this->db->where($where)->update('app_invoice', array('shop_id' => $shop_id['data']));
                if ($user_invoice) {
                    send_json(array('code' => 0, 'data' => '', 'msg' => "添加成功"));
                } else {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "同步失败"));
                }
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "添加失败"));
            }

        }

    }

    //删除个人中心发票抬头
    public function invoice_del()
    {
        $customer_id = $this->session->customer_id;
        $post        = $this->input->post();
        $data['id']  = $post['id'];
        $query       = $this->db->query("SELECT * FROM app_invoice WHERE id=" . $data['id']);
        $r_info      = $query->row_array();
        if (!empty($data['id'])) {
            $res = $this->db->where(array("id" => $data['id'], "customer_id" => $r_info['customer_id']))->delete('app_invoice');
            if ($res == true) {
                send_json(array('code' => 0, 'data' => '', 'msg' => '删除成功'));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => '删除失败'));
            }
        }
        send_json(array('code' => -1, 'data' => '', 'msg' => 'id不存在'));
    }

    //设置默认发票抬头
    public function invoice_default()
    {
        $customer_id = $this->session->customer_id;
        $post        = $this->input->post();
        $data['id']  = $post['id'];
        if ($data['id']) {
            $boo22 = $this->db->where(array("customer_id" => $customer_id))->update('app_invoice', ['is_default' => 0]);
            $bool1 = $this->db->where(array("id" => $data['id']))->update('app_invoice', ['is_default' => 1]);
            if ($bool1 && $boo22) {
                send_json(array('code' => 0, 'data' => '', 'msg' => '设置成功'));
            }

        }

    }

    //收货地址
    public function address()
    {
        $customer_id = $this->session->customer_id;
        if ($customer_id) {
            $query          = $this->db->query("SELECT * FROM app_address  WHERE customer_id=" . $customer_id);
            $r_info         = $query->result_array();
            $r_info['data'] = $r_info;
            $this->load->view('member/address', $r_info);
        }
    }

    //修改默认地址
    public function chanage_default_address()
    {
        $customer_id  = $this->session->customer_id;
        $shop_user_id = $this->user_model->customer_id_to_shop_user_id($customer_id);
        $new          = $_GET['new_id'];
        if (!$new) {
            send_json(array('code' => 1, 'data' => '', 'msg' => "参数错误"));
        }
        $this->user_model->change_user_default_address_byid($customer_id, $new);
        //同步默认地址
        $data            = array('shop_user_id' => $shop_user_id);
        $adderss         = $this->db->select('shop_id,id')->where(array("id" => $new))->from('app_address')->get()->row_array();
        $data['shop_id'] = $adderss['shop_id'];
        $this->member_model->company_user_address_default($data);
        send_json(array('code' => 0, 'data' => '', 'msg' => '设置成功'));
    }

    //个人中心修改/添加收货地址
    public function address_add()
    {

        $customer_id         = $this->session->customer_id;
        $post                = $this->input->post();
        $data['customer_id'] = $customer_id;
        $data['name']        = $post['name'];
        if (empty($data['name'])) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "姓名不能为空"));
        }
        $data['province'] = $post['province'];
        if (empty($data['province'])) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "省份不能为空"));
        }
        $data['city'] = $post['city'];
        if (empty($data['city'])) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "城市不能为空"));
        }
        $data['district'] = $post['district'];
        if (empty($data['district'])) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "地区能为空"));
        }

        $data['address'] = $post['address'];
        if (empty($data['address'])) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "街道地址不能为空"));
        }
        $data['postcode'] = isset($post['postcode']) ? $post['postcode'] : "";

        $data['phone'] = $post['phone'];
        if (empty($data['phone'])) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "手机号不能为空"));
        }
//        $data['tel']=isset($post['tel']) ? $post['tel']:"";
        $data['tel'] = $post['tel'];

        $data['region_id'] = $post['regionId'];
        if (!empty($post['id'])) {
            $this->db->where(array("id" => $post['id']))->update('app_address', $data);
            //获取商城shop_user_id
            $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($customer_id);
            //获取商城地址shop_id
            $adderss         = $this->db->select('shop_id,id')->where(array("id" => $post['id']))->from('app_address')->get()->row_array();
            $data['shop_id'] = $adderss['shop_id'];
            //同步修改地址
            $data['region_name'] = $post['province'] . $post['city'] . $post['district'];
            $this->member_model->company_user_address($data);
            // 设置默认地址
            if (isset($post['is_default'])) {
                $this->user_model->change_user_default_address_byid($customer_id, $adderss['id']);
                //同步默认地址
                $this->member_model->company_user_address_default($data);
            }
            send_json(array('code' => 0, 'data' => '', 'msg' => '修改成功'));
        } else {
            $where   = array('customer_id' => $customer_id, 'is_default' => 1);
            $adderss = $this->db->where($where)->get('app_address')->row_array();
            if ($adderss) {
                $data['is_default'] = 0;
            } else {
                $data['is_default'] = 1;
            }

            $res = $this->db->insert('app_address', $data);
            if ($res) {
                $data['id'] = $this->db->insert_id();
                //获取商城shop_user_id
                $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($customer_id);
                //同步新增地址
                $data['region_name'] = $post['province'] . $post['city'] . $post['district'];
                $user_address        = $this->member_model->company_user_address($data);

                if ($data['is_default'] == 1) {
                    $data['shop_id'] = $user_address;
                    $this->member_model->company_user_address_default($data);
                }
                $this->db->where(array("id" => $data['id']))->update('app_address', array('shop_id' => $user_address));
            }
            if ($data['id']) {
                // 设置默认地址
                if (isset($post['is_default'])) {
                    $this->user_model->change_user_default_address_byid($customer_id, $data['id']);
                    //同步默认地址
                    $data['shop_id'] = $user_address;
                    $this->member_model->company_user_address_default($data);
                }
                send_json(array('code' => 0, 'data' => '', 'msg' => "添加成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => '添加失败'));
            }
        }
    }

    //设为默认地址
    public function address_default()
    {
        $customer_id = $this->session->customer_id;
        $identity    = $this->session->customer_info['identity'];
        $post        = $this->input->post();
        //获取商城shop_user_id
        $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($customer_id);
        //获取商城地址shop_id
        $adderss         = $this->db->select('shop_id')->where(array("id" => $post['id']))->from('app_address')->get()->row_array();
        $data['shop_id'] = $adderss['shop_id'];

        $row = $this->user_model->change_user_default_address_byid($customer_id, $post['id']);
        if ($row) {
            //同步默认地址
            $address_default = $this->member_model->company_user_address_default($data);
            send_json(array('code' => 0, 'data' => '', 'msg' => '设置成功'));
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => '设置失败'));
        }

    }

    //删除收货地址
    public function address_del()
    {
        $customer_id = $this->session->customer_id;
        $post        = $this->input->post();
        $data['id']  = $post['id'];
//        $query = $this->db->query("SELECT * FROM app_address WHERE id=". $data['id']);
        //        $r_info = $query->row_array();
        if (!empty($data['id'])) {
            $res = $this->db->where(array("id" => $data['id'], "customer_id" => $customer_id))->delete('app_address');
            if ($res == true) {
                send_json(array('code' => 0, 'data' => '', 'msg' => '删除成功'));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => '删除失败'));
            }
        }
        send_json(array('code' => -1, 'data' => '', 'msg' => 'id不存在'));
    }

    //修改密码页面
    public function personal_password()
    {
        $customer_id = $this->session->customer_id;
        if ($customer_id) {
            $query  = $this->db->query("SELECT * FROM app_manager_user WHERE customer_id=" . $customer_id);
            $r_info = $query->row_array();
            $this->load->view('member/personal_password', $r_info);
        }

    }

    //修改密码
    public function password_edit()
    {
        $customer_id = $this->session->customer_id;
        $query       = $this->db->query("SELECT * FROM app_manager_user WHERE customer_id=" . $customer_id);
        $r_info      = $query->row_array();
        $post        = $this->input->post();
        if ($post['password']) {
            $url              = $this->config->item("shop_url") . 'companymanagerapi/company_user_pass_word/';
            $data_arr['time'] = time();
            $data_arr['key']  = md5($this->config->item("token_const_wjyh") . $data_arr['time']);
            //获取商城shop_user_id
            $data_arr['uid']      = $this->user_model->customer_id_to_shop_user_id($customer_id);
            $data_arr['password'] = $post['password'];
            $rs                   = curl_request($url, $data_arr);
            $rs                   = json_decode($rs, true);
            if ($rs['code'] == 200) {
                $data['password'] = isset($post['new_password']) ? $post['new_password'] : "";
                if ($post['password'] == $post['new_password']) {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "新密码与旧密码相同"));
                }
                //获取商城shop_user_id
                $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($customer_id);
                $quers                = $this->db->set('password', $data['password'])->where('customer_id', $customer_id)->update('app_manager_user');
                if ($quers) {
                    $res = $this->customer_model->company_user_edit($data);
                    if ($res) {
                        send_json(array('code' => 0, 'data' => '', 'msg' => "修改成功"));
                    } else {
                        send_json(array('code' => -1, 'data' => '', 'msg' => "同步失败"));
                    }
                } else {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "修改失败"));
                }
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "旧密码错误"));
            }
        }
    }

    //逐次还款页面
    public function bill_time()
    {
        $customer_id = $this->session->customer_id;
        $identity    = $this->session->customer_info['identity'];

        $arr = $this->customer_model->get_customer_user($customer_id);

        $str = join(',', $arr);

        $data['admin'] = $this->db->where(array('customer_id' => $customer_id))->get('app_admin')->row_array();

        $sql = 'select  sum(money) as moneyTotal  from  app_bill  where  (status = 0) AND (type = 2) AND (customer_id in (' . $str . '))';

        $data['unpayorder'] = $this->db->query($sql)->row_array();

        $sql                         = 'select  id  from  app_bill  where  (status = 0) AND (type = 2) AND (customer_id in (' . $str . '))';
        $data['unpayorder']['count'] = count($this->db->query($sql)->result_array());

        $sql           = 'select  sum(money) as moneyTotal  from  app_bill where customer_id in (' . $str . ') AND (type = 2)';
        $data['order'] = $this->db->query($sql)->row_array();

        $sql                    = 'select  id  from  app_bill  where customer_id in (' . $str . ') AND (type = 2)';
        $data['order']['count'] = count($this->db->query($sql)->result_array());
        $where                  = '';

        if (isset($_GET['id'])) {
            $id                = $_GET['id'];
            $data['status_id'] = $id;
            if ($id || $id == "0") {
                $where = $where . ' AND a.status=' . $id;
            } else {
                $where = '';
            }

        } else {
            $id                = "";
            $data['status_id'] = '';
        }

        if (isset($_GET['ordersn'])) {
            $ordersn         = $_GET['ordersn'];
            $data['ordersn'] = $ordersn;
            if ($ordersn) {
                $where = $where . " AND c.order_bn='" . $ordersn . "'";
            } else {
                $where = '';
            }
        } else {
            $data['ordersn'] = '';
        }

        if (isset($_GET['date'])) {
            $date                = $_GET['date'];
            $data['status_date'] = $date;
            $date1               = strtotime(date('Y-m', strtotime($date)));
            $date2               = strtotime(date('Y-m', strtotime($date . "+1 month")));
            if ($date) {
                $where = $where . " AND UNIX_TIMESTAMP(a.created_at) between '" . $date1 . "' AND '" . $date2 . "'";
            } else {
                $where = $where . '';
            }
        } else {
            $date                = date('Y-m-d', time());
            $date1               = strtotime(date('Y-m', strtotime($date)));
            $date2               = strtotime(date('Y-m', strtotime($date . "+1 month")));
            $where               = $where . " AND UNIX_TIMESTAMP(a.created_at) between '" . $date1 . "' AND '" . $date2 . "'";
            $data['status_date'] = '';
        }

        //分页
        $listRows = 10; //每页数量
        $sql      = 'select a.id from  app_bill as a ,app_customer as b , app_order as c,app_order_bill as d where a.customer_id = b.id AND (a.type = 2) AND d.bill_id=a.id AND d.order_id=c.id ' . $where . ' AND a.customer_id in (' . $str . ')';

        $count = count($this->db->query($sql)->result_array());

        $num = $count / $listRows;

        if (floor($num) == $num) {
            $num = floor($num);
        } else {
            $num = floor($num) + 1;
        }
        if (isset($_GET['p'])) {
            $nowPage = $_GET['p'];
        } else {
            $nowPage = 1;
        }

        if ($nowPage < $num) {
            $data['nexturl'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?p=' . ($nowPage + 1) . '&id=' . $id . '&date=' . $date;
        } else {
            $data['nexturl'] = 'javascript:;';
        }
        if ($nowPage > 1) {
            $data['preurl'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?p=' . ($nowPage - 1) . '&id=' . $id . '&date=' . $date;
        } else {
            $data['preurl'] = 'javascript:;';
        }

        $firstRow = $listRows * ($nowPage - 1);

        $data['nowPage'] = $nowPage;

        $sql = 'select a.status as st,a.money as zq_money,c.payment_at as order_payment_at,c.order_bn as order_bn,b.username as username,a.should_repayment_date as should_repayment_date,a.actual_repayment_date as actual_repayment_date , a.bill_bn as bill_bn from  app_bill as a ,app_customer as b , app_order as c,app_order_bill as d where a.customer_id = b.id AND d.bill_id=a.id AND d.order_id=c.id ' . $where . '  AND a.customer_id in (' . $str . ') AND (a.type = 2) limit ' . $firstRow . ',' . $listRows . '';

        $data['result'] = $this->db->query($sql)->result_array();

        $this->load->view('member/bill_time', $data);
    }

    //账期逐月
    public function bill_month()
    {
        $customer_id = $this->session->customer_id;
        $identity    = $this->session->customer_info['identity'];
        $arr         = $this->customer_model->get_customer_user($customer_id);

        $str = join(',', $arr);

        $data['admin'] = $this->db->from('app_admin')->where(array('customer_id' => $customer_id))->get()->row_array();

        $sql                       = 'select  sum(money) as moneyTotal,bill_bn,start_repayment_date,should_repayment_date,status from app_bill join app_bill_month on app_bill_month.bill_id = app_bill.id  where app_bill_month.bill_date is not null AND  (status = 0) AND (type=1) AND (customer_id in (' . $str . '))';
        $data['unpayorder']        = $this->db->query($sql)->row_array();
        $data['unpayorder']['day'] = ceil((strtotime($data['unpayorder']['should_repayment_date']) - time()) / 86400);
        if ($data['unpayorder']['day'] < 0 || $data['unpayorder']['day'] == 0) {
            $data['unpayorder']['day'] = 0;
        }

        $where = '';
        if (isset($_GET['date'])) {
            $date                = $_GET['date'];
            $data['status_date'] = $date;
            $date1               = strtotime(date('Y-m', strtotime($date)));
            $date2               = strtotime(date('Y-m', strtotime($date . "+1 month")));
            if ($date) {
                $where = $where . " AND UNIX_TIMESTAMP(c.bill_date) between '" . $date1 . "' AND '" . $date2 . "'";
            } else {
                $where = $where . '';
            }
        } else {
            $date                = date('Y-m-d', time());
            $date1               = strtotime(date('Y-m', strtotime($date)));
            $date2               = strtotime(date('Y-m', strtotime($date . "+1 month")));
            $where               = $where . " AND UNIX_TIMESTAMP(c.bill_date) between '" . $date1 . "' AND '" . $date2 . "'";
            $data['status_date'] = $date;
        }
        $sql = 'select a.id as bill_id, a.bill_bn as bill_bn,c.bill_date_from as bill_date_from,c.bill_date_to as bill_date_to,c.bill_date as bill_date,a.start_repayment_date as start_repayment_date,a.should_repayment_date as should_repayment_date,a.actual_repayment_date as actual_repayment_date,count(b.id) as count ,a.status as st,a.money as zq_money FROM app_bill AS a JOIN app_bill_month AS c on c.bill_id = a.id LEFT JOIN app_order_bill AS d on a.id = d.bill_id LEFT JOIN app_order AS b on d.order_id = b.id WHERE 1=1 ' . $where . ' AND (type=1) AND a.customer_id in (' . $str . ')';

        $data['res'] = $this->db->query($sql)->result_array();

        $data['result'] = array();
        foreach ($data['res'] as $k => $v) {
            if ($v['bill_id']) {
                $data['result'][] = $v;
                $list             = $v;
            } else {
                $list['bill_id'] = "";
            }
        }

        $sql                         = "select a.id from app_order as a,app_order_bill as b,app_bill as c where a.id=b.order_id AND b.bill_id=c.id AND c.bill_bn ='" . $data['unpayorder']['bill_bn'] . "'";
        $data['unpayorder']['count'] = count($this->db->query($sql)->result_array());

        $sql           = 'select  sum(money) as moneyTotal  from  app_order  where customer_id in (' . $str . ') AND payment_method=9';
        $data['order'] = $this->db->query($sql)->row_array();

        $sql                    = 'select  id  from  app_order  where customer_id in (' . $str . ') AND payment_method=9';
        $data['order']['count'] = count($this->db->query($sql)->result_array());

        $listRows = 10; //每页数量
        $sql      = "select a.id from app_order as a,app_order_bill as b,app_bill as c,app_customer as d where b.order_id=a.id AND c.id=b.bill_id AND a.customer_id=d.id AND c.id='" . $list['bill_id'] . "' AND a.customer_id in ('" . $str . "')";
        $count    = count($this->db->query($sql)->result_array());

        $num = $count / $listRows;

        if (floor($num) == $num) {
            $num = floor($num);
        } else {
            $num = floor($num) + 1;
        }

        if (isset($_GET['p'])) {
            $nowPage = $_GET['p'];
        } else {
            $nowPage = 1;
        }

        if ($nowPage < $num) {
            $data['nexturl'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?p=' . ($nowPage + 1) . '&date=' . $date;
        } else {
            $data['nexturl'] = 'javascript:;';
        }
        if ($nowPage > 1) {
            $data['preurl'] = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?p=' . ($nowPage - 1) . '&date=' . $date;
        } else {
            $data['preurl'] = 'javascript:;';
        }

        $firstRow = $listRows * ($nowPage - 1);
        $sql      = "select a.id as order_id,a.invoice as invoice,d.username as user_name,d.name as u_name,d.tel as user_tel,a.money as order_money,a.payment_at as order_payment_at,a.status as order_status  from  app_order as a,app_order_bill as b,app_bill as c,app_customer as d where b.order_id=a.id AND c.id=b.bill_id AND a.customer_id=d.id AND c.id='" . $list['bill_id'] . "' limit " . $firstRow . "," . $listRows . " ";
        $data['order']['list'] = $this->db->query($sql)->result_array();
        $data['total_page']    = ceil($count / 10);
        $data['nowPage']       = $nowPage;
        $this->load->view('member/bill_month', $data);
    }

    //企业发票
    public function business_invoice()
    {
        $customer_id = $this->session->customer_id;
        $customer_id = 3;
        if ($customer_id) {
            $billss       = $this->db->where('b.customer_id', $customer_id)->from('app_bill_invoice b')->get();
            $bills        = $billss->result_array();
            $bill_invoice = array();
            foreach ($bills as $key => $bil) {
                if (isset($bil['id'])) {
                    $order = $this->db->where('bill_id', $bil['id'])->from('app_order_bill b')
                        ->join('app_order o', 'o.id=b.order_id')->get();
                    $order = $order->result_array();
                    $money = array();
                    foreach ($order as $key => $or) {
                        $bills[$bil['id']]['money'][$key] = $or['money'];
                    }
                    $bills[$bil['id']]['cata'] = $order;
                }
            }
            $data['invoice'] = $bills;
            $data['order']   = $bill_invoice;
        }
        if ($_POST) {
            $add                = array();
            $add['customer_id'] = $customer_id;
            $bills              = $this->db->from('app_bill_invoice')->where('customer_id=', $customer_id);
            if (!empty($_POST['price_min'])) {
                $add['invoice_bn']  = $_POST['price_min'];
                $invoice_bn         = $_POST['price_min'];
                $data['invoice_bn'] = $invoice_bn;
                $bills->where('invoice_bn=', $invoice_bn);
            }
            if (!empty($_POST['modules'])) {
                $add['invoice_type']  = $_POST['modules'];
                $invoice_type         = $_POST['modules'];
                $data['invoice_type'] = $invoice_type;
                $bills->where('invoice_type=', $invoice_type);
            }
            if (!empty($_POST['enddate'])) {
                $created_at2         = $_POST['enddate'];
                $data['created_at2'] = $created_at2;
                $bills->where('created_at<=', $created_at2);
            }
            if (!empty($_POST['stratdate'])) {
                $created_at1         = $_POST['stratdate'];
                $data['created_at1'] = $created_at1;

                $bills->where('created_at>=', $created_at1);
            }
            $bills        = $bills->get()->result_array();
            $bill_invoice = array();
            foreach ($bills as $key => $bil) {
                if (isset($bil['id'])) {
                    $order = $this->db->where('bill_id', $bil['id'])->from('app_order_bill b')
                        ->join('app_order o', 'o.id=b.order_id')->get();
                    $order                    = $order->result_array();
                    $bill_invoice[$bil['id']] = $order;
                }
            }

            $data['invoice'] = $bills;
            $data['order']   = $bill_invoice;
//            print_r( $data['invoice']);
        }
        $this->load->view('member/business_invoice', $data);
    }
//    public function ceshi()
    //    {
    //        $url                 = 'http://119.23.141.210:10226/order_api/update_order_status';
    //        $data_arr['order_bn']    = '1010180410040008';
    //        $data_arr['shop_customer_id']     = ' 8038';
    //        $data_arr['created_at'] = '2018-04-10 15:56:06';
    //        $data_arr['payment_at'] =  '2018-04-10 17:32:42';
    //
    //        $data_arr['money']     = 406.86;
    //        $data_arr['shop_order_id']     =   6937;
    //        $data_arr['express_fee']     = 153.00;
    //
    //        $data_arr['status']     = 3;
    //
    //       // $data_arr['order_at'] = "2013-05-06";
    //        $data_arr['order_info']     = json_encode(array('id'=>0,'name'=>2));
    //
    //        $data_arr['shipping_at'] = "2013-05-06";
    //        $data_arr['time_stamp']     = time();
    //
    //        $data_arr['token']  = create_token($data_arr,$this->config->item("token_const"));;
    //
    //        echo $data_arr['token'];
    //        $data_arr =
    //        $rs     = curl_request($url, $data_arr);
    //        var_dump($rs);
    //
    //        $result            = json_decode($rs, true);
    //
    //
    //    }

}
